package com.huluobo.a2302mdmdemo.videos.pages

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player.REPEAT_MODE_ONE
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.navigation.NavHostController
import com.google.gson.Gson
import com.huluobo.lib_base.entity.VideoEntityItem
import com.huluobo.lib_http.Const
import com.tencent.mmkv.MMKV

/**
 *  Created by LC on 2025/8/4.
 */

@Composable
fun VideoPage(navHostController: NavHostController) {
    val videoEntityJson = MMKV.defaultMMKV().decodeString(Const.KEY_VIDEO)
    val videoEntityItem = Gson().fromJson(videoEntityJson, VideoEntityItem::class.java)
    val context = LocalContext.current

    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            //添加播放源
            setMediaItem(MediaItem.fromUri(videoEntityItem.videopath))
            //准备
            prepare()
            //是否自动播放
            playWhenReady = true
            //重复模式
            repeatMode = REPEAT_MODE_ONE
        }

//        val player = ExoPlayer.Builder(context).build()
//        player.setMediaItem()
//        player.prepare()
//        player.playWhenReady = true
//        player.repeatMode = REPEAT_MODE_ONE
    }

    Column(
        Modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        AndroidView(factory = {
            PlayerView(it).apply {
                player = exoPlayer
                useController = true
            }
        }, modifier = Modifier.fillMaxSize())
    }

    DisposableEffect(Unit) {
        //相当于activity中的onDestroy
        onDispose {
            //释放当前播放器,防止内存泄漏
            exoPlayer.release()
        }
    }
}